#include <unordered_map>
#include <queue>
#include <algorithm>
using namespace std;
class Solution
{
    struct my_pair
    {
        my_pair(pair<const int, int> pair)
            : val(pair.first), frequent(pair.second) { ; }
        bool operator>(const my_pair &my_pair) const
        {
            return frequent > my_pair.frequent;
        }
        int val;
        int frequent;
    };
// top k + 数据结构 + stl原理 + C++基础
public:
    vector<int> topKFrequent(vector<int> &nums, int k)
    {
        unordered_map<int, int> count_map;
        for (auto e : nums)
            count_map[e]++;
        priority_queue<my_pair, vector<my_pair>, greater<my_pair>> heap;
        for (auto it = count_map.begin(); it != count_map.end(); it++)
        {
            heap.push(*it);
            if (heap.size() > k)
                heap.pop();
        }
        vector<int> res;
        while (heap.size())
        {
            res.push_back(heap.top().val);
            heap.pop();
        }
        return res;
    }
};